package com.jiaomatech.tencent.cos.listener;

import com.qcloud.cos.COSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;

import java.util.Map;

/**
 * Description: 监听closed事件 .<br>
 *
 * @author jm
 *     Created By 2018/9/27 上午10:37
 */
public class CosClosedListener implements ApplicationListener<ContextClosedEvent> {

    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CosClosedListener.class);

    /**
     * 当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时，该事件被发布.
     * 一个已关闭的上下文到达生命周期末端；它不能被刷新或重启.
     *
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        Map<String, COSClient> cosClientMap = event.getApplicationContext()
            .getBeansOfType(COSClient.class);
        LOGGER.info("[ {} 个 COS 连接将会被断开]", cosClientMap.size());
        cosClientMap.keySet().forEach(beanName -> {
            cosClientMap.get(beanName).shutdown();
            LOGGER.info("[COS 连接 {} 被断开]", beanName);
        });
    }
}
